import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import ProTable from '@ant-design/pro-table';
import {
  Button,
  Tabs,
  Modal,
  Table,
  message,
  Row,
  DatePicker,
  Col,
  Form,
  Tooltip,
  Select,
  InputNumber,
} from 'antd';
import { sortTran, filterTran } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import dayjs from 'dayjs';
import {
  addMaintenanceInfo,
  delMaintenanceInfo,
  getMaintenanceInfoByIdentification,
  updateMaintenanceInfo,
  getMaintenanceCommissioners,
  getMaintenanceInfoByPage,
  getMaintenanceHours,
} from '@/services/device/maintenanceInfo';
import { tableSearchPublicConfig } from '@/utils/filterUtils';
import moment from 'moment';

const MaintenanceInfo: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [modalVisit1, setModalVisit1] = useState(false); // 查看弹窗
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState(''); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [id1, setIndentufication] = useState();
  const [people, setPeople] = useState([]);
  const [form] = Form.useForm();
  const ref = useRef(null);
  const [usedTime, setUsedTime] = useState(1);
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      align: 'center',
      sorter: true,
      width: 80,
    },
    /*  {
      title: '唯一标识',
      dataIndex: 'identification',
      hideInTable: true,
    }, */
    {
      title: '维修记录编号',
      dataIndex: 'maintenanceid',
      align: 'center',
      sorter: true,
    },
    {
      title: '设备名称',
      dataIndex: 'deviceName',
      align: 'center',
      sorter: true,
    },
    /* {
      title: '设备编号',
      dataIndex: 'deviceid',
    },
    {
      title: '故障时间',
      dataIndex: 'faultTime',
    }, */
    {
      title: '故障描述',
      dataIndex: 'faultDesc',
      align: 'center',
      sorter: true,

      search: false,
    },
    {
      title: '指派人员',
      dataIndex: 'assignedTo',
      align: 'center',
      sorter: true,
      search: false,
    },
    {
      title: '维修开始时间',
      dataIndex: 'beginMaintenance',
      align: 'center',
      sorter: true,

      search: false,
      render: (text, record) => <a>{moment(record.beginMaintenance).format('YYYY-MM-DD HH:mm')}</a>,
    },
    {
      title: '维修结束时间',
      dataIndex: 'endMaintenance',
      align: 'center',
      sorter: true,

      search: false,
      render: (text, record) => <a>{moment(record.endMaintenance).format('YYYY-MM-DD HH:mm')}</a>,
    },
    {
      title: '维修工时',
      search: false,
      dataIndex: 'costTime',
      align: 'center',
      sorter: true,

      render: (text, record, _, action) => (
        <span>{dayjs(record.endMaintenance).diff(dayjs(record.beginMaintenance), 'hours')}</span>
      ) /* {
        dayjs(record.endMaintenance).diff(dayjs(record.beginMaintenance), 'hour');
        const startDate = moment("2020-5-20");
        const endDate = moment(new Date())
        const workDayCount = endDate.diff(startDate,'days')
        <span>
      } */,
    },
    {
      title: '服务备注',
      dataIndex: 'serviceNotes',
      search: false,
      align: 'center',
      sorter: true,

      onCell: () => {
        return {
          style: {
            maxWidth: 100,
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            cursor: 'pointer',
          },
        };
      },
      render: (text) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '状态',
      align: 'center',
      sorter: true,

      dataIndex: 'state',

      valueType: 'select',
      fieldProps: {
        options: [
          {
            label: '未开始',
            value: '未开始',
          },
          {
            label: '进行中',
            value: '进行中',
          },
          {
            label: '已完成',
            value: '已完成',
          },
        ],
      },
    },
    /* {
      title: '创建时间',
      dataIndex: 'createTime',
    }, */
    /* {
      title: '创建人',
      dataIndex: 'createBy',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
    },
    {
      title: '更新人',
      dataIndex: 'updateBy',
    }, */
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 180,
      render: (text, record, _, action) => [
        <a
          key="detailKey"
          onClick={() => {
            setModalVisit(true);
            setFormTitle('查看');
            setCreateOrUpdate(true);
            form.setFieldsValue({
              identification: record.identification,
              maintenanceid: record.maintenanceid,
              deviceName: record.deviceName,
              deviceid: record.deviceid,
              faultTime: moment(record.faultTime),
              faultDesc: record.faultDesc,
              assignedTo: record.assignedTo,
              beginMaintenance: moment(record.beginMaintenance),
              endMaintenance: moment(record.endMaintenance),
              costTime: moment(record.endMaintenance).diff(
                moment(record.beginMaintenance),
                'hours',
              ),
              serviceNotes: record.serviceNotes,
              state: record.state,
              createTime: moment(record.createTime),
              /* createBy: record.createBy,
              updateTime: moment(record.updateTime),
              updateBy: record.updateBy, */
              id: record.id,
            });
          }}
        >
          查看
        </a>,
        <a
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(false);
            setFormTitle('编辑');
            form.setFieldsValue({
              identification: record.identification,
              maintenanceid: record.maintenanceid,
              deviceName: record.deviceName,
              deviceid: record.deviceid,
              faultTime: moment(record.faultTime),
              faultDesc: record.faultDesc,
              assignedTo: record.assignedTo,
              beginMaintenance: moment(record.beginMaintenance),
              endMaintenance: moment(record.endMaintenance),
              costTime: moment(record.endMaintenance).diff(
                moment(record.beginMaintenance),
                'hours',
              ),
              serviceNotes: record.serviceNotes,
              state: record.state,
              createTime: moment(record.createTime),
              /* createBy: record.createBy,
              updateTime: moment(record.updateTime),
              updateBy: record.updateBy, */
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delMaintenanceInfo({ id: record.id });
                actionRef.current.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  const handleSubmit = async (values) => {
    setConfirmLoading(true);
    console.log(formTitle, '标题');
    console.log('提交的数据', values);
    const re = form.getFieldsValue();
    if (dayjs(re.beginMaintenance).isBefore(dayjs(re.endMaintenance))) {
      if (formTitle == '新建') {
        const result = await addMaintenanceInfo(values);
        console.log(result, 'jieguo;');
        if (result != null) {
          message.success('添加成功');
        }
      } else if (formTitle == '编辑') {
        await updateMaintenanceInfo(values);
      } else {
        setCreateOrUpdate(false);
      }
      setConfirmLoading(false);
      setModalVisit(false);
      actionRef.current.reload();
    } else {
      message.warning('维修结束时间需要晚于开始时间！');
    }
  };
  const handleTime = async (values) => {
    const info = form.getFieldsValue();
    console.log('表单信息：', info);
    const time1 = moment(info.beginMaintenance, 'YYYY-MM-DD HH:mm:ss');
    const time2 = moment(info.endMaintenance, 'YYYY-MM-DD HH:mm:ss');
    if (time1 !== null && time2 !== null) {
      const seconds = time2.diff(time1, 'seconds');
      const hours = Math.floor(seconds / 36) / 100;
      if (hours > 0) {
        info.costTime = hours;
        form.setFieldsValue(info);
      } else {
        message.warning('开始时间需早于结束时间！');
      }
    }
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="维护记录"
        search={tableSearchPublicConfig}
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setCreateOrUpdate(false);
              setFormTitle('新建');
              form.resetFields();
              setModalVisit(true);
            }}
            type="primary"
          >
            新建
          </Button>,
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              const filters = filterTran(ref.current.getFieldsValue());
              exportSpareInfo({
                current: 1,
                pageSize: 5000,
                filters: filters,
              }).then((res) => {
                const aLink = document.createElement('a');
                document.body.appendChild(aLink);
                aLink.style.display = 'none';
                aLink.href = window.URL.createObjectURL(res);
                aLink.setAttribute('download', `MaintenanceInfo.xls`);
                aLink.click();
                document.body.removeChild(aLink);
              });
            }}
            type="primary"
          >
            导出
          </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          const sorters = sortTran(sort);
          const filters = filterTran(params);
          const result = await getMaintenanceInfoByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          console.log('获取到的维护记录:', result);
          const temp = await getMaintenanceCommissioners();
          const info: any[] = [];
          console.log('获取到的人员', temp);
          if (temp != null) {
            temp.data.map((item: any) => {
              info.push({ label: item, value: item });
            });
          }
          setPeople(info);
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 1500, y: 350 }}
        rowSelection={{}}
      />
      <ModalForm
        layout="horizontal"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        visible={modalVisit}
        title={formTitle}
        form={form}
        onFinish={handleSubmit}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setModalVisit(false);
          },
        }}
      >
        <ProFormText name="id" label="id" placeholder="请输入名称" hidden={true} />
        <ProFormText
          name="identification"
          label="唯一标识"
          rules={[{ required: true, message: '请输入唯一标识' }]}
          disabled={createOrUpdate}
          hidden={true}
          initialValue={11}
        />
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormText
              name="maintenanceid"
              label="维修记录编号"
              rules={[{ required: true, message: '请输入维修记录编号!' }]}
              disabled={createOrUpdate}
            />
          </Col>
          <Col span={12}>
            <Form.Item
              name="state"
              label="状态"
              rules={[{ required: true, message: '请选择状态!' }]}
            >
              <Select disabled={createOrUpdate}>
                <Select.Option value="未开始">未开始</Select.Option>
                <Select.Option value="进行中">进行中</Select.Option>
                <Select.Option value="已完成">已完成</Select.Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormText
              name="deviceName"
              label="设备名称"
              disabled={createOrUpdate}
              rules={[{ required: true, message: '请输入设备名称!' }]}
            />
          </Col>
          <Col span={12}>
            {/* <ProFormText name="deviceid" label="设备编号" disabled={createOrUpdate} /> */}
            <ProFormText
              name="faultDesc"
              label="故障描述"
              disabled={createOrUpdate}
              rules={[{ required: true, message: '请输入故障描述!' }]}
            />
          </Col>
        </Row>
        {/* <Row gutter={[50, 0]}>
          <Col span={12}>
            <Form.Item name="faultTime" label="故障时间">
              <DatePicker
                style={{ width: 350 }}
                format="YYYY-MM-DD HH:mm:ss"
                showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
                disabled={createOrUpdate}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <ProFormText name="faultDesc" label="故障描述" disabled={createOrUpdate} />
          </Col>
        </Row> */}
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <Form.Item
              name="beginMaintenance"
              label="维修开始"
              // rules={[{ required: true,   message: '请选择维修开始时间!' }]}
            >
              <DatePicker
                style={{ width: '100%' }}
                showTime={{
                  format: 'HH:mm',
                }}
                onChange={handleTime}
                format="YYYY-MM-DD HH:mm"
                disabled={createOrUpdate}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="endMaintenance"
              label="维修结束"
              // rules={[{ required: true, message: '请选择维修结束时间!' }]}
            >
              <DatePicker
                style={{ width: '100%' }}
                showTime={{
                  format: 'HH:mm',
                }}
                onChange={handleTime}
                format="YYYY-MM-DD HH:mm"
                disabled={createOrUpdate}
              />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            {/* <ProFormText
              name="assignedTo"
              label="指派人员"
              // rules={[{ required: false, message: '请输入服务备注!' }]}
              disabled={createOrUpdate}
            /> */}

            <ProFormSelect
              mode="tags"
              name="assignedTo"
              label="指派人员"
              options={people}
              disabled={createOrUpdate}
              // rules={[{ required: true, message: '请选择指派人员!' }]}
            />
          </Col>
          <Col span={12}>
            <Form.Item
              label="维修工时"
              name="costTime"

              // rules={[{ required: true, message: '请输入!' }]}
            >
              <InputNumber
                addonAfter="h"
                style={{ width: '100%' }}
                min={0}
                max={99999}
                step={1}
                disabled
                // onChange={(e) => handlestandManufactWorkHourChange(e.target.value)}
              />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormText
              name="serviceNotes"
              label="服务备注"
              rules={[{ required: false, message: '请输入服务备注!' }]}
              disabled={createOrUpdate}
            />
          </Col>
          <Col span={12} />
        </Row>
        {/* <Row gutter={[50, 0]}>
          <Col span={12}>
            <Form.Item name="createTime" label="创建时间">
              <DatePicker disabled={createOrUpdate} style={{ width: 350 }} />
            </Form.Item>
          </Col>
          { <Col span={12}>
            <ProFormText name="createBy" label="创建人" disabled={createOrUpdate} />
          </Col>}
        </Row> */}
        {/* <Row gutter={[50, 0]}>
          <Col span={12}>
            <Form.Item name="updateTime" label="更新时间">
              <DatePicker disabled={createOrUpdate} style={{ width: 350 }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <ProFormText name="updateBy" label="更新人" disabled={createOrUpdate} />
          </Col>
        </Row> */}
      </ModalForm>
      {/* <Modal
        open={modalVisit1}
        title="巡检详细"
        destroyOnClose
        width={1500}
        onCancel={() => {
          setModalVisit1(false);
        }}
        footer={[]}
      >
        
      </Modal> */}
    </PageHeaderWrapper>
  );
};
export default MaintenanceInfo;
